package com.miniapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miniapp.entity.Permission;
import com.miniapp.entity.RolePermission;
import com.miniapp.mapper.PermissionMapper;
import com.miniapp.mapper.RolePermissionMapper;
import com.miniapp.service.PermissionService;
import com.miniapp.domain.vo.PermissionQueryVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 权限Service实现类
 *
 * @author yourname
 * @date 2025-09-08
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Resource
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public List<Permission> getPermissionsByRoleIds(List<Long> roleIds) {
        if (CollectionUtils.isEmpty(roleIds)) {
            return new ArrayList<>();
        }
        return baseMapper.selectByRoleIds(roleIds);
    }

    @Override
    public List<String> getPermissionCodesByRoleId(Long roleId) {
        if (roleId == null) {
            return new ArrayList<>();
        }
        return baseMapper.selectPermissionCodesByRoleId(roleId);
    }

    @Override
    public List<Permission> queryPermissionPage(PermissionQueryVO queryVO) {
        Page<Permission> page = new Page<>(queryVO.getPageNum(), queryVO.getPageSize());
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();

        // 权限名称模糊查询
        if (queryVO.getPermissionName() != null) {
            queryWrapper.like(Permission::getPermissionName, queryVO.getPermissionName());
        }
        // 权限编码模糊查询
        if (queryVO.getPermissionCode() != null) {
            queryWrapper.like(Permission::getPermissionCode, queryVO.getPermissionCode());
        }
        // URL模糊查询
        if (queryVO.getUrl() != null) {
            queryWrapper.like(Permission::getUrl, queryVO.getUrl());
        }

        queryWrapper.orderByDesc(Permission::getCreateTime);

        IPage<Permission> permissionPage = baseMapper.selectPage(page, queryWrapper);
        return permissionPage.getRecords();
    }

    @Override
    public boolean savePermission(Permission permission) {
        // 检查权限编码是否已存在
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Permission::getPermissionCode, permission.getPermissionCode());
        long count = baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new RuntimeException("权限编码已存在");
        }
        return save(permission);
    }

    @Override
    public boolean updatePermission(Permission permission) {
        // 检查权限编码是否已被其他权限使用
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Permission::getPermissionCode, permission.getPermissionCode())
                .ne(Permission::getId, permission.getId());
        long count = baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new RuntimeException("权限编码已存在");
        }
        return updateById(permission);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean assignRolePermissions(Long roleId, List<Long> permissionIds) {
        // 先删除角色原有权限
        rolePermissionMapper.deleteByRoleId(roleId);

        // 如果权限ID列表为空，直接返回
        if (CollectionUtils.isEmpty(permissionIds)) {
            return true;
        }

        // 批量插入新的权限关联
        List<RolePermission> rolePermissionList = new ArrayList<>();
        for (Long permissionId : permissionIds) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            rolePermissionList.add(rolePermission);
        }

        return rolePermissionMapper.batchInsert(rolePermissionList) > 0;
    }
}
